/*
* Copyright 2011 Andy Lee.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package uk.co.optimisticpanda.remoteweb.command

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class CommandUtils {

	static Closure execute = {it.execute()}
	static Closure display = {println it.description}
	static Closure containers  = {
		if (it.children){
			println it.description
		}
	}

	static void traverse(commands, c){
		commands.each { recurseTraversal(c, it) }

	}
	private static void recurseTraversal(c, child){
		if(child.children){
			c(child)
			child.children.each{ recurseTraversal(c, it) }
		}else c(child)
	}

	static List<Command> findAllParents(commands, int targetLevel=0){
		List<Command> result = []
		recurseFindMatching(result, targetLevel, 0 , commands, { it.children});
		return result
	}

	static List<Command> findAllLeaves(commands, int targetLevel=0){
		List<Command> result = []
		recurseFindMatching(result, targetLevel, 0 , commands, { !it.children});
		return result
	}

	private static void recurseFindMatching(result, int targetLevel, int currentLevel, children, c){
		if(targetLevel == currentLevel){
			result.addAll( children.findAll(c)  );
		}else{
			int nextLevel = currentLevel + 1
			children.findAll({it.children }).each{
				recurseFindMatching(result, targetLevel, nextLevel, it.children, c)
			}
		}
	}
}
